package com.threeti.mecool.mobile.controller;

import com.threeti.mecool.core.application.message.ConnectionInfo;
import com.threeti.mecool.core.application.message.MessageService;
import com.threeti.mecool.core.domain.model.acl.User;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.mobile.Commander;
import com.threeti.mecool.mobile.interfaces.ResponserDto;
import com.threeti.mecool.mobile.interfaces.assembler.UserAssembler;
import com.threeti.mecool.mobile.interfaces.dto.UserDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

import static com.threeti.mecool.mobile.MessageConst.*;

/**
 * @author Jay Meng
 */
@Controller
@RequestMapping(value = "/auth")
public class AuthMobiController {
    Logger logger = LoggerFactory.getLogger(AuthMobiController.class);
    @Autowired
    UserRepository userRepository;
    @Autowired
    private MessageService messageService;

    @RequestMapping(value = "/login")
    @ResponseBody
    public ResponserDto login(@Valid UserDto userDto, BindingResult result) throws Exception {
        try {
            String command = Commander.command();
            if (result.hasFieldErrors("loginName") || result.hasFieldErrors("password"))
                return ResponserDto.withBizFailureMsg(command, MSG_AUTH_002);

            if (result.hasFieldErrors("imei"))
                return ResponserDto.withBizFailureMsg(command, MSG_AUTH_003);

            User user = userRepository.findByloginNameAndPassword(userDto.getLoginName(), userDto.getPassword());
            if (user == null) {
                return ResponserDto.withBizFailureMsg(command, MSG_AUTH_001);
            }

            if (1 != user.getDisableImeiValidate() && !user.getImei().equals(userDto.getImei())) {
                return ResponserDto.withBizFailureMsg(command, MSG_AUTH_004);
            }

            messageService.confirmAccount(userDto.getLoginName());
            ResponserDto ret = ResponserDto.successCommand(command);
            ret.withBizSuccessBody("user", UserAssembler.toDto(user));

            // Create message server connection parameters.
            ConnectionInfo connectionInfo = new ConnectionInfo();
            connectionInfo.setHost(messageService.getMobileHost());
            connectionInfo.setPort(messageService.getMobilePort());
            connectionInfo.setService(messageService.getService());
            connectionInfo.setPassword(messageService.getAccountPassword(userDto.getLoginName()));
            ret.withBizSuccessBody("messageServer", connectionInfo);
            return ret;
        } catch (Exception e) {
            logger.error("!!! LOGIN !!!", e);
            throw e;
        }
    }

    public void setUserRepository(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void setMessageService(MessageService messageService) {
        this.messageService = messageService;
    }
}
